<template>
  <div class="constant-category">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>常数项管理</span>
          <!-- 添加查询输入框和查询按钮 -->
          <el-input v-model="searchCode" placeholder="输入常数项编码查询" style="width: 200px; margin-right: 10px;"></el-input>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button type="primary" @click="handleCreate">新增</el-button>
        </div>
      </template>
      
      <el-table :data="itemList" style="width: 100%">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="constanttypeid" label="类别ID" width="100" />
        <el-table-column prop="constantcode" label="编码" width="120" />
        <el-table-column prop="constantname" label="名称" />
        <el-table-column label="操作" width="180">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    
    <!-- 表单对话框 -->
    <el-dialog v-model="dialogVisible" title="常数项表单" width="30%">
      <el-form :model="form" label-width="80px">
        <el-form-item label="类别ID">
          <el-input v-model="form.constanttypeid" placeholder="输入类别ID" />
        </el-form-item>
        <el-form-item label="编码">
          <el-input v-model="form.constantcode" placeholder="输入编码" />
        </el-form-item>
        <el-form-item label="名称">
          <el-input v-model="form.constantname" placeholder="输入名称" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSave">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getConstantItemList, addConstantItem, updateConstantItem, deleteConstantItem, getConstantItemByCode } from '@/api/constantitem'

// 数据状态
const itemList = ref([])
const dialogVisible = ref(false)
const form = ref({
  id: null,
  constanttypeid: null,
  constantcode: '',
  constantname: ''
})
const currentAction = ref('create') // create/update
const loading = ref(false) // 加载状态
const searchCode = ref('') // 查询输入框的值

// 生命周期钩子 - 组件挂载时获取数据
onMounted(() => {
  fetchData()
})

const fetchData = async () => {
  loading.value = true
  try {
    const response = await getConstantItemList()
    console.log('API响应:', response) // 打印完整响应，用于调试
    itemList.value = response
  } catch (error) {
    console.error('获取常数项列表失败', error)
    
    // 区分不同类型的错误
    if (error.response) {
      // 服务器返回错误状态码
      ElMessage.error(`请求失败: ${error.response.status} ${error.response.statusText}`)
    } else if (error.request) {
      // 请求已发送，但没有收到响应
      ElMessage.error('服务器未响应，请检查网络连接')
    } else {
      // 其他错误
      ElMessage.error('发生错误: ' + error.message)
    }
  } finally {
    loading.value = false
  }
}

// 新增
const handleCreate = () => {
  resetForm()
  dialogVisible.value = true
  currentAction.value = 'create'
}

// 编辑
const handleEdit = (row) => {
  form.value = { ...row }
  dialogVisible.value = true
  currentAction.value = 'update'
}

// 重置表单
const resetForm = () => {
  form.value = {
    id: null,
    constanttypeid: null,
    constantcode: '',
    constantname: ''
  }
}

// 保存
const handleSave = async () => {
  try {
    let result
    if (currentAction.value === 'create') {
      result = await addConstantItem(form.value)
    } else {
      result = await updateConstantItem(form.value)
    }
    
    if (result) {
      dialogVisible.value = false
      ElMessage.success(currentAction.value === 'create' ? '新增成功' : '更新成功')
      fetchData() // 重新获取数据
    } else {
      ElMessage.error('操作失败')
    }
  } catch (error) {
    console.error('保存失败', error)
    ElMessage.error('操作失败，请检查网络连接')
  }
}

// 删除
const handleDelete = async (row) => {
  try {
    // 确认对话框
    await ElMessageBox.confirm('确定要删除这个常数项吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const result = await deleteConstantItem(row.id)
    if (result) {
      ElMessage.success('删除成功')
      fetchData() // 重新获取数据
    } else {
      ElMessage.error('删除失败')
    }
  } catch (error) {
    // 用户取消操作
    if (error.name !== 'CancelError') {
      console.error('删除失败', error)
      ElMessage.error('删除失败，请检查网络连接')
    }
  }
}

// 根据常数项编码查询
const handleSearch = async () => {
  if (!searchCode.value) {
    // 如果输入框为空，获取所有常数项列表
    fetchData()
    return
  }
  loading.value = true
  try {
    const response = await getConstantItemByCode(searchCode.value)
    if (response) {
      itemList.value = [response]
    } else {
      itemList.value = []
      ElMessage.warning('未找到匹配的常数项')
    }
  } catch (error) {
    console.error('根据常数项编码查询失败', error)
    ElMessage.error('查询失败，请检查网络连接')
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.constant-category {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>